﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.SharePoint;
using System.Reflection;

namespace ListItemEditor
{
    public class GridViewDataSourceSPQuery : GridViewDataSourceSiteData
    {
        protected override DataTable InternalGetDataTable(SPWeb web, SPList list)
        {
            SPListItemCollection items = InternalGetListItems(web, list);
            return this.GetDataTableFromItems(items);
        }

        protected override bool IsFieldTypeNotAllowed(SPField field)
        {
            return (field is SPFieldCalculated);
        }

        protected override string GetEffectiveRootFolder(GridViewDataSourceSettings settings)
        {
            return settings.RootFolder;
        }

        protected virtual DataTable GetDataTableFromItems(SPListItemCollection items)
        {
            return items.GetDataTable();
        }

        protected virtual SPListItemCollection InternalGetListItems(SPWeb web, SPList list)
        { 
            SPQuery query = new SPQuery();
            query.ViewAttributes = "Scope=\"" + Settings.ViewScope + "\" ModerationType=\"Moderator\"";
            if (Settings.ViewScope != ViewScope.Recursive && Settings.ViewScope != ViewScope.RecursiveAll && !string.IsNullOrEmpty(Settings.RootFolder))
            {
                query.Folder = web.GetFolder(Settings.RootFolder);
            }

            if (!string.IsNullOrEmpty(Settings.Query)) query.Query = Settings.Query;
            if (Settings.RowLimit > 0) query.RowLimit = Settings.RowLimit;

            List<string> effectiveViewFields = this.GetEffectiveViewFields (list is SPDocumentLibrary);
            if (effectiveViewFields != null && effectiveViewFields.Count > 0) query.ViewFields = FormatViewFields2(effectiveViewFields);

            SPListItemCollection coll = list.GetItems(query);
            return coll;
        }

        protected string FormatViewFields2(List<string> viewFields)
        {
            return string.Concat(viewFields.Select(s => string.Format("<FieldRef Name=\"{0}\" />", s)).ToArray());
        }
    }
}